﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;//需要引用的命名空间
using System.Text;//需要引用的命名空间

/// <summary>
/// validateCode 的摘要说明
/// </summary>
/// 
 namespace ValidateCode
{
public class validateCode
{
    HttpContext context;
	public validateCode(HttpContext context)
	{
        this.context = context;
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
    Random rd = new Random();
    public string GetCode(int length)
    {
        StringBuilder sb = new StringBuilder();
        char[] chs = new char[] {'a','b','c','d','e','f','g','h',
                                 'k','m','n','p','q','r','s','t',
                                 '2','3','4','5','6','7','8','9'};
        int cIndex = 0;
        for (int i = 0; i < length; i++)
        {
            cIndex = rd.Next(0, chs.Length);
            sb.Append(chs[cIndex]);
        }
        return sb.ToString();

    }

    public void CreateValidateImage(string validateCode, int width, int height)
    {
        if (validateCode.Length == 0)
        {
            return;
        }
        //Bitmap位图（画布）,Graphics人
        using (Bitmap bmp = new Bitmap(width, height))
        {
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.Clear(Color.White);
                Font font = new Font("黑体", 28, FontStyle.Bold);
                //LinearGradientBrush这个刷子能画出颜色渐变效果
                Brush br = new System.Drawing.Drawing2D.LinearGradientBrush
                    (new Rectangle(0, 0, width, height),
                    Color.DarkGreen, Color.Red, 1.2f, true);
                //添加噪点
                for (int i = 0; i < 50; i++)
                {
                    int x1 = rd.Next(1, width - 2);
                    int y1 = rd.Next(1, height - 2);
                    int x2 = x1 + 2;
                    int y2 = y1 + 2;
                    g.DrawLine(Pens.Orange, x1, y1, x2, y2);
                }
                g.DrawString(validateCode, font, br, 2, -2);
                for (int i = 0; i < 50; i++)
                {
                    int x1 = rd.Next(1, width - 2);
                    int y1 = rd.Next(1, height - 2);
                    int x2 = x1 + 2;
                    int y2 = y1 + 2;
                    g.DrawLine(Pens.SkyBlue, x1, y1, x2, y2);
                }
                g.DrawRectangle(Pens.Black, 0, 0, width - 2, height - 2);
                //把验证码写到cookie，没有写到硬盘，而是使用的是缓存cookie
                HttpCookie vCodeCookie = new HttpCookie("vCode", validateCode);
                context.Response.Cookies.Add(vCodeCookie);
                this.context.Response.ContentType = "image/jpeg";
                bmp.Save(this.context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }
}
}